package com.menu.web.controller.product;

import com.menu.common.annotation.Log;
import com.menu.common.core.controller.BaseController;
import com.menu.common.core.domain.AjaxResult;
import com.menu.common.core.domain.entity.MenuProtype;
import com.menu.common.core.page.TableDataInfo;
import com.menu.common.enums.BusinessType;
import com.menu.common.enums.DataSourceType;
import com.menu.common.utils.SecurityUtils;
import com.menu.common.utils.poi.ExcelUtil;
import com.menu.framework.datasource.DynamicDataSourceContextHolder;
import com.menu.system.domain.MenuProducts;
import com.menu.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 产品信息Controller
 *
 * @author ruoyi
 * @date 2024-06-05
 */
@RestController
@RequestMapping("/system/products")
public class MenuProductsController extends BaseController {
    @Autowired
    private IMenuProductsService menuProductsService;
    @Autowired
    private IMenuInformtypeService menuInformtypeService;
    @Autowired
    private IMenuProtypeService menuProtypeService;
    @Autowired
    private IMenuProductInfoService menuProductInfoService;
    @Autowired
    private IreceptionRoleService receptionRoleService;
    @Autowired
    private ISysRoleService sysRoleService;

    /**
     * 查询角色信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:products:list')")
    @GetMapping("/list")
    public TableDataInfo list(MenuProducts menuProducts) {
        startPage();
        List<MenuProducts> list = menuProductsService.selectMenuProductsList(menuProducts);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('system:products:list')")
    @GetMapping("/typetemplates")
    public AjaxResult typetemplates(MenuProducts menuProducts) {

        return AjaxResult.success(menuProductsService.selectMenuProductsList(menuProducts));
    }

    //查询产品属性
    @PreAuthorize("@ss.hasPermi('system:products:list')")
    @GetMapping("/menuProducts")
    public TableDataInfo menuProducts(MenuProducts menuProducts) {
        startPage();
        List<MenuProducts> list = menuProductsService.selectmenuProducts(menuProducts);
        return getDataTable(list);
    }/*下载模板*/

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<MenuProducts> util = new ExcelUtil<MenuProducts>(MenuProducts.class);
        util.importTemplateExcel(response, "产品模板");
    }

    /**
     * 导出角色信息列表
     */
//    @PreAuthorize("@ss.hasPermi('system:products:export')")
    @Log(title = "产品信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MenuProducts menuProducts) {
        List<MenuProducts> list = menuProductsService.selectMenuProductsListExecl(menuProducts);
        ExcelUtil<MenuProducts> util = new ExcelUtil<MenuProducts>(MenuProducts.class);
        util.exportExcel(response, list, "角色信息数据");
    }

    @Log(title = "产品导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:products:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<MenuProducts> util = new ExcelUtil<MenuProducts>(MenuProducts.class);
        List<MenuProducts> menuProducts = util.importExcel(file.getInputStream());
        for (MenuProducts menuProduct : menuProducts) {
            menuProductsService.insertMenuProducts(menuProduct, MenuProducts.inserType.IMPORT.getInfo());
        }


        return success("导入成功");
    }

    /**
     * 获取角色信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:products:query')")
    @GetMapping(value = "/{productId}")
    public AjaxResult getInfo(@PathVariable("productId") Long productId) {
        AjaxResult ajax = AjaxResult.success();

        MenuProducts menuProducts=new MenuProducts();
        ajax.put(AjaxResult.DATA_TAG, menuProductsService.selectMenuProductsByProductId(productId));
        ajax.put("products", menuProtypeService.selectMenuProtypeByorder(3L));
        ajax.put("prodTypes", menuProductInfoService.selectMenuProductInfoids(productId));
        ajax.put("receptionRole", receptionRoleService.selectreceptionRoleList(null));
        ajax.put("roles", menuProductInfoService.selectMenuProductInfoRoles(productId));
        ajax.put("heartbeatProducts", menuProductsService.selectMenuProductsList(menuProducts));
        ajax.put("heartbeatProductIds", menuProductsService.findMenuHeartbeatproducts(productId));
        return ajax;

    }
    @PreAuthorize("@ss.hasPermi('system:products:query')")
    @GetMapping(value = "/productRole/{productId}")
    public AjaxResult getproductRole(@PathVariable("productId") Long productId) {
        AjaxResult ajax = AjaxResult.success();
        ajax.put(AjaxResult.DATA_TAG, menuProductsService.selectMenuProductsByProductId(productId));
        ajax.put("roles", menuProductsService.queryUserProduct(productId));
        return ajax;

    }
    @PreAuthorize("@ss.hasPermi('system:products:query')")
    @GetMapping(value = "/adds")
    public AjaxResult getInfoAdd() {


        AjaxResult ajax = AjaxResult.success();
        ajax.put("products", menuProtypeService.selectMenuProtypeByorder(2L));

        ajax.put("receptionRole", receptionRoleService.selectreceptionRoleList(null));
        return ajax;

    }

    @PreAuthorize("@ss.hasPermi('system:products:query')")
    @GetMapping(value = "/findProductIds/{proTypeId}")
    public AjaxResult findProductIds(@PathVariable("proTypeId") Long proTypeId) {
        MenuProducts menuProducts = new MenuProducts();
        menuProducts.setProdTypeId(proTypeId);

        AjaxResult ajax = AjaxResult.success();

        ajax.put("heartbeatProducts", menuProductsService.selectMenuProductsList(menuProducts));

        return ajax;

    }

    /**
     * 新增角色信息
     */
    @PreAuthorize("@ss.hasPermi('system:products:add')")
    @Log(title = "产品信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MenuProducts menuProducts) {
        if (menuProducts.getProdTypes() == null || menuProducts.getProdTypes().length == 0) {
            return AjaxResult.warn(DynamicDataSourceContextHolder.getDataSourceType().equals(DataSourceType.MASTER.name()) ? "请选择产品类别" : "Please select a product category");
        }
        if (menuProducts.getIsPublish().equals("0")) {
            return toAjax(menuProductsService.insertMenuProducts(menuProducts, MenuProducts.inserType.INSERT.getInfo()));
        } else {
            if (menuProducts.getSellingPoint() == null) {
                return AjaxResult.warn(DynamicDataSourceContextHolder.getDataSourceType().equals(DataSourceType.MASTER.name()) ? "请填写产品卖点" : "Please fill in the product selling point");
            }
            return toAjax(menuProductsService.insertMenuProducts(menuProducts, MenuProducts.inserType.INSERT.getInfo()));
        }


    }

    /**
     * 修改角色信息
     */

    @Log(title = "角色信息", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('system:products:edit')")
    @PutMapping
    public AjaxResult edit(@RequestBody MenuProducts menuProducts) {
        //非 admin
        if(!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {

            List<Long> longs = menuProductsService.queryUserProduct(menuProducts.getProductId());
            if (!longs.isEmpty()) {
                /*获取当前登录角色*/
                List<Long> longs1 = sysRoleService.UserRoles(getUserId());

                if(!longs1.stream().allMatch(longs::contains)){
                    return AjaxResult.error(DynamicDataSourceContextHolder.getDataSourceType().equals(DataSourceType.MASTER.name()) ? menuProducts.getProductName()+"-无权限修改" :  menuProducts.getProductName()+"-Modify without permission");
                }

            }
        }

        if (menuProducts.getProdTypes() == null || menuProducts.getProdTypes().length == 0) {
            return AjaxResult.warn(DynamicDataSourceContextHolder.getDataSourceType().equals(DataSourceType.MASTER.name()) ? "请选择产品类别" : "Please select a product category");
        }
        if (menuProducts.getIsPublish().equals("1")) {
            if (menuProducts.getSellingPoint() == null) {
                return AjaxResult.warn(DynamicDataSourceContextHolder.getDataSourceType().equals(DataSourceType.MASTER.name()) ? "请填写产品卖点" : "Please fill in the product selling point");
            }
        }

        return toAjax(menuProductsService.updateMenuProducts(menuProducts));
    }

    @Log(title = "角色信息", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('system:products:edit')")
    @PutMapping("/editProductRole")
    public AjaxResult editProductRole(@RequestBody MenuProducts menuProducts) {
        //非 admin
       if(menuProducts.getRoles().length==0) {
           return AjaxResult.error(DynamicDataSourceContextHolder.getDataSourceType().equals(DataSourceType.MASTER.name()) ?"请选择角色":"Please select a role");
       }

       return  menuProductsService.editProductRole(menuProducts);
    }
    /**
     * 删除角色信息
     */
    @PreAuthorize("@ss.hasPermi('system:products:remove')")
    @Log(title = "角色信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{productIds}")
    public AjaxResult remove(@PathVariable Long[] productIds) {
        if(SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            return toAjax(menuProductsService.deleteMenuProductsByProductIds(productIds));
        }
        /*是否admin建立*/
        for (Long productId : productIds) {
            List<Long> longs = menuProductsService.queryUserProduct(productId);

            if (!longs.isEmpty()) {
                /*获取当前登录角色*/
                List<Long> longs1 = sysRoleService.UserRoles(getUserId());

                if(!longs1.stream().allMatch(longs::contains)){
                    return AjaxResult.error(DynamicDataSourceContextHolder.getDataSourceType().equals(DataSourceType.MASTER.name()) ? menuProductsService.selectMenuProductsByProductId(productId).getProductName()+"-无权限删除" :  menuProductsService.selectMenuProductsByProductId(productId).getProductName()+"-Delete without permission");
                }

            }



        }


        return toAjax(menuProductsService.deleteMenuProductsByProductIds(productIds));
    }

    @GetMapping("/treeselect")
    public AjaxResult treeselect(MenuProtype menuProtype) {
        List<MenuProtype> menus = menuProtypeService.selectMenuProtypeList(menuProtype);
        return success(menuProtypeService.buildMenuTreeSelect(menus));
    }


}
